using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Decav.Web.Properties;

namespace Decav.Web.Controls
{
    /// <summary>
    /// Chooses a date using a set of drop down boxes for input.
    /// </summary>
    public class DateSelectionBox : WebControl
    {
        public DateSelectionBox()
            : base(HtmlTextWriterTag.Span)
        {
        }

        public string MonthBoxClientId
        {
            get
            {
                return string.Format("{0}_Month", ClientID);
            }
        }

        public string DayBoxClientId
        {
            get
            {
                return string.Format("{0}_Day", ClientID);
            }
        }

        public string YearBoxClientId
        {
            get
            {
                return string.Format("{0}_Year", ClientID);
            }
        }

        public DateTime Value
        {
            get
            {
                if (_curDateTime != DateTime.MinValue)
                    return _curDateTime;

                if (ViewState["Value"] == null)
                    return DateTime.MinValue;
                else
                    return (DateTime)ViewState["Value"];
            }
            set
            {
                _curDateTime = value;
                IsValid = true;
                ViewState["Value"] = value;
            }
        }

        /// <summary>
        /// Gets if the controls current value is valid.
        /// </summary>
        public bool IsValid
        {
            get
            {
                if (ViewState["IsValid"] == null)
                    return true;

                return (bool)ViewState["IsValid"];
            }
            protected set
            {
                ViewState["IsValid"] = value;
            }
        }

        private DateTime _curDateTime = DateTime.MinValue;

        protected override void OnInit(EventArgs e)
        {
            string monthPost = Page.Request.Form[MonthBoxClientId];
            string dayPost = Page.Request.Form[DayBoxClientId];
            string yearPost = Page.Request.Form[YearBoxClientId];

            string newStr = string.Format("{0}/{1}/{2}",
                monthPost == null ? string.Empty : monthPost.Trim(),
                dayPost == null ? string.Empty : dayPost.Trim(),
                yearPost == null ? string.Empty : yearPost.Trim());

            DateTime newValue = DateTime.MinValue;
            if (newStr == "//")
            {
                Value = DateTime.MinValue;
            }
            else if (DateTime.TryParse(newStr, out newValue))
            {
                Value = newValue;
            }
            else
            {
                Value = DateTime.MinValue;
                IsValid = false;
            }

            base.OnInit(e);
        }


        private void AddInputBoxAttributes(HtmlTextWriter writer, string id, int length, decimal widthEm, string value)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Id, id);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, id);
            writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Value, value);
            writer.AddStyleAttribute("border", "solid 0px white");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, string.Format("{0}em", widthEm));
            writer.AddStyleAttribute(HtmlTextWriterStyle.MarginTop, "2px");
        }

        private void SetUnsetStyle(HtmlTextWriterStyle style, string value)
        {
            if (this.Style[style] == null || this.Style[style].Trim().Length == 0)
                this.Style[style] = value;
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (_curDateTime != DateTime.MinValue)
                Value = _curDateTime;

            SetUnsetStyle(HtmlTextWriterStyle.BorderColor, "#CCCCCC");
            SetUnsetStyle(HtmlTextWriterStyle.BorderStyle, "solid");
            SetUnsetStyle(HtmlTextWriterStyle.BorderWidth, "1px");
            SetUnsetStyle(HtmlTextWriterStyle.BackgroundColor, "white");

            Page.ClientScript.RegisterStartupScript(
                typeof(DateSelectionBox), ClientID,
                _javascript.Replace("$CLIENTID$", ClientID),
                true);

            Page.ClientScript.RegisterClientScriptResource(typeof(DateSelectionBox),
                "Decav.Web.DecavDateBoxJavascript.js");

            base.OnPreRender(e);
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            bool isnull = Value == DateTime.MinValue;

            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Span);

            AddInputBoxAttributes(writer, MonthBoxClientId, 2, 1.1m, isnull ? string.Empty : Value.Month.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();

            writer.Write(" / ");

            AddInputBoxAttributes(writer, DayBoxClientId, 2, 1.1m, isnull ? string.Empty : Value.Day.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();

            writer.Write(" / ");

            AddInputBoxAttributes(writer, YearBoxClientId, 4, 2.1m, isnull ? string.Empty : Value.Year.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();

            writer.RenderEndTag(); // SPAN
        }

        private const string _javascript = @"var $CLIENTID$ = new DecavDateBox(""$CLIENTID$"");";
    }
}
